package com.ks.utils.dbBack;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;

public abstract class DatabaseBackup {

	public DatabaseBackup() {
		super();
	}

	public String packPath(String savePath, String fileName) {
		File saveFile = new File(savePath);
		if (!saveFile.exists()) {// 如果目录不存在
			saveFile.mkdirs();// 创建文件夹
		}
		if (!savePath.endsWith(File.separator)) {
			savePath = savePath + File.separator;
		}
		return savePath + fileName;
	}

	public abstract String packCommendExec();

	/**
	 * 
	 * 返回true表示导出成功，否则返回false。
	 * 
	 * @return
	 */
	public abstract boolean backup();

	public static void load() {
		try {
			String fPath = "c:/test.sql";
			Runtime rt = Runtime.getRuntime();
			// 调用 mysql 安装目录的命令
			Process child = rt.exec("C://Program Files//MySQL//MySQL Server 5.1//bin//mysql -u root -p root dlgs_test");

			OutputStream out = child.getOutputStream();// 控制台的输入信息作为输出流
			String inStr;
			StringBuffer sb = new StringBuffer("");
			String outStr;
			BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(fPath), "utf-8"));
			while ((inStr = br.readLine()) != null) {
				sb.append(inStr + "\r\n");
			}
			outStr = sb.toString();
			System.out.println(outStr);
			OutputStreamWriter writer = new OutputStreamWriter(out, "utf-8");
			System.out.println("7777777777777777777777777777777777777");
			writer.write(outStr);
			System.out.println("888888888888888888888888888888888888888");
			writer.flush();
			out.close();
			br.close();
			writer.close();
			System.out.println("");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static void load1() {
		try {
			String fPath = "c:/test.sql";
			Runtime rt = Runtime.getRuntime();

			// 调用 mysql 的 cmd:
			Process child = rt
					.exec("C://Program Files//MySQL//MySQL Server 5.1//bin//mysql.exe -uroot -proot dlgs_test ");
			OutputStream out = child.getOutputStream();// 控制台的输入信息作为输出流
			String inStr;
			StringBuffer sb = new StringBuffer("");
			String outStr;
			BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(fPath), "utf8"));
			while ((inStr = br.readLine()) != null) {
				sb.append(inStr + "\r\n");
			}
			outStr = sb.toString();

			OutputStreamWriter writer = new OutputStreamWriter(out, "utf8");
			writer.write(outStr);
			// 注：这里如果用缓冲方式写入文件的话，会导致中文乱码，用flush()方法则可以避免
			writer.flush();
			// 别忘记关闭输入输出流
			out.close();
			br.close();
			writer.close();

			System.out.println("");

		} catch (Exception e) {
			e.printStackTrace();
		}

	}

}
